package com.like.entity;

import org.xutils.DbManager;
import org.xutils.x;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;

public class SupportBaseM {

	public Context mContext;
	protected DbManager mDbManager;

	private Activity mActivity;
	private DialogFragment mLoadingDialog;
	private Handler mHandler;
	private Runnable mShowLoadingRunnable;
	private String mTag = "";

	public SupportBaseM(Activity activity) {
		mContext = activity;
		mHandler = new Handler();
		this.mActivity = activity;
		this.mTag = activity.getClass().getName();
		mShowLoadingRunnable = new Runnable() {
			@Override
			public void run() {
				try {
					showLoading(true);
				} catch (Exception e) {
				}
			}
		};
	}

	public SupportBaseM(Fragment fragment) {
		this(fragment.getActivity());
		this.mTag = fragment.getClass().getName();
	}

	public SupportBaseM(FragmentActivity activity, DialogFragment loadingDialog) {
		this(activity);
		this.mLoadingDialog = loadingDialog;
	}

	public SupportBaseM(Fragment fragment, DialogFragment loadingDialog) {
		this(fragment);
		this.mLoadingDialog = loadingDialog;
	}

	public DbManager getDbManager() {
		if (mDbManager == null) {
			DbManager.DaoConfig daoConfig = new DbManager.DaoConfig();
			mDbManager = x.getDb(daoConfig);
		}
		return mDbManager;
	}

	public DbManager getDbManager(String dbName) {
		if (mDbManager == null) {
			DbManager.DaoConfig daoConfig = new DbManager.DaoConfig()
					.setDbName(dbName);
			mDbManager = x.getDb(daoConfig);
		}
		return mDbManager;
	}

	public void setLoadingDialog(DialogFragment loadingDialog) {
		this.mLoadingDialog = loadingDialog;
	}

	public void showLoading(boolean show) {
		try {
			if (mLoadingDialog == null)
				return;
			if (show) {
				if (mActivity instanceof FragmentActivity) {
					if (!mLoadingDialog.isAdded())
						mLoadingDialog.show(((FragmentActivity) mActivity)
								.getSupportFragmentManager(), mTag);
				}
			} else {
				mHandler.removeCallbacks(mShowLoadingRunnable);
				if (mLoadingDialog != null
						&& mLoadingDialog.getDialog() != null
						&& mLoadingDialog.isAdded())
					mLoadingDialog.dismiss();
			}
		} catch (Exception e) {
		}
	}

	public void showLoading(boolean show, long delayTime) {
		try {
			if (show)
				mHandler.postDelayed(mShowLoadingRunnable, delayTime);
			else {
				mHandler.removeCallbacks(mShowLoadingRunnable);
				showLoading(false);
			}
		} catch (Exception e) {
		}
	}
}
